<template>
  <div class="number-input">
    <div
      class="number-input__minus"
      :class="{ disable: value <= min }"
      @click="onMinus"
    >
      -
    </div>
    <input
      class="number-input__input"
      type="text"
      :value="value"
      @input="onInput"
      @blur="$event.target.value=value"
    />
    <div
      class="number-input__add"
      :class="{ disable: value >= max }"
      @click="onAdd"
    >
      +
    </div>
  </div>
</template>

<script>
export default {
  name: "NumberInput",
  props: {
    value: {
      type: Number,
      required: true,
    },
    min: {
      // 允许输入的最小值
      type: Number,
      default: 1,
    },
    max: {
      // 允许输入的最大值
      type: Number,
      default: 99,
    },
  },
  model: {
    prop: "value",
    event: "change",
  },
  methods: {
    onMinus() {
      if (this.value <= this.min) return;
      this.$emit("change", this.value - 1);
    },
    onAdd() {
      if (this.value >= this.max) return;
      this.$emit("change", this.value + 1);
    },
    onInput($event) {
      const val = $event.target.value;

      // 检测用户的输入是不是合法的，合法就发出change事件，带上最新的数值
      if (/^\d+$/.test(val) && val >= this.min && val <= this.max) {
        this.$emit("change", Number(val));
      } else {
        if (!$event.target.value.trim()) return;
        // 用户的输入如果不合法 就让数据复原
        $event.target.value = this.value;
      }
    },
  },
};
</script>

<style lang="scss" scoped>
$border-color: #e0e0e0;

.number-input {
  display: inline-flex;
  width: 175px;
  height: 52px;
  color: #747474;

  input {
    width: 55px;
    border: 1px solid $border-color;
    outline: none;
    text-align: center;
    font-size: 22px;
    padding: 0;
    box-sizing: border-box;
  }

  &__add,
  &__minus {
    width: 60px;
    text-align: center;
    border: 1px solid $border-color;
    line-height: 48px;
    font-size: 32px;
    cursor: pointer;
    user-select: none;
  }

  &__add {
    border-left: none;
    border-top-right-radius: 5px;
    border-bottom-right-radius: 5px;
  }

  &__minus {
    border-right: none;
    border-top-left-radius: 5px;
    border-bottom-left-radius: 5px;
  }

  .disable {
    border-color: #eee;
    color: #dcdcdc;
  }
}
</style>
